package com.brspace.qualitycontrol.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brspace.qualitycontrol.entity.*;
import com.brspace.qualitycontrol.entity.Process;
import com.brspace.qualitycontrol.entity.vo.*;
import com.brspace.qualitycontrol.mapper.*;
import com.brspace.qualitycontrol.service.CollectWritService;
import com.brspace.qualitycontrol.utils.EmptyUtil;
import com.brspace.qualitycontrol.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 收文 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-04-07
 */
@Service
public class CollectWritServiceImpl extends ServiceImpl<CollectWritMapper, CollectWrit> implements CollectWritService {

    @Resource
    private CollectWritMapper collectWritMapper;
    @Resource
    private HandleMapper handleMapper;
    @Resource
    private ProcessNodeMapper processNodeMapper;
    @Resource
    private ProcessMapper processMapper;
    @Resource
    private ProcessRouterMapper processRouterMapper;

    /**
     * 收文列表
     * @param pageParam
     * @param
     * @return
     */
    @Override
    public IPage<CollectWrit> selectPage(Page<CollectWrit> pageParam, CollertWritVo collertWritVo) {
        QueryWrapper<CollectWrit> queryWrapper = new QueryWrapper<>();
        if (collertWritVo==null) {
            return baseMapper.selectPage(pageParam,queryWrapper);
        }
        String title = collertWritVo.getTitle();
        String writNum = collertWritVo.getWritNum();
        String putWrit1 = collertWritVo.getPutWritBigin();
        String putWrit2 = collertWritVo.getPutWritEnd();
        String comeWrit = collertWritVo.getComeWrit();
        String state = collertWritVo.getState();
        if (!EmptyUtil.isEmpty(title)) {
            queryWrapper.like("title",title);
        }
        if (!EmptyUtil.isEmpty(state)) {
            queryWrapper.likeRight("state",state);
        }
        if (!EmptyUtil.isEmpty(writNum)) {
            queryWrapper.like("writ_num",writNum);
        }
        if (!EmptyUtil.isEmpty(comeWrit)) {
            queryWrapper.like("come_writ",comeWrit);
        }
        if (!EmptyUtil.isEmpty(putWrit1)) {
            queryWrapper.ge("put_writ",putWrit1);
        }
        if (!EmptyUtil.isEmpty(putWrit2)) {
            queryWrapper.le("put_writ",putWrit2);
        }
        return baseMapper.selectPage(pageParam,queryWrapper);
    }

    //分页查询当前用户未阅/已阅收文列表
    @Override
    public PaginationVo<CollectWrit> getPullList(Integer pageNum, Integer pageSize, String userId, Integer isRead) {
        PaginationVo<CollectWrit> vo = new PaginationVo<>();
        //pageNum:查询的页数，pageSize:一页显示的数量
        PageHelper.startPage(pageNum,pageSize);
        List<CollectWrit> consumerList = collectWritMapper.getPullList(userId,isRead);
        //获取总记录数pageInfo.getTotal()
        PageInfo<CollectWrit> pageInfo = new PageInfo<>(consumerList);
        vo.setTotal(Integer.parseInt(String.valueOf(pageInfo.getTotal())));
        vo.setDataList(consumerList);
        return vo;
    }

    //每月统计收文数量
    @Override
    public List<MonthNumVo> statisticsByMonth() {
        return collectWritMapper.statisticsByMonth();
    }

    //计算今年收文数量和去年收文数量
    @Override
    public R getNowAndLastNum() {
        R r = new R();
        //计算今年的收文数量
        Integer nowNum = collectWritMapper.getNowNum();
        //计算去年的收文数量
        Integer lastNum = collectWritMapper.getLastNum();
        return r.data("now",nowNum).data("last",lastNum);
    }

    //收文类型统计列表
    @Override
    public R getTypeNumList() {
        List<TypeVo> list = collectWritMapper.getTypeNumList();
        return R.ok().data("list",list);
    }

    /**
     *保存收文
     *@author Hugo
     *@date 2021-04-28 14:55
     **/
    @Override
    public void saveInfo(CollectWrit collectWrit) {

        if (collectWrit.getWritNum() == "" || collectWrit.getWritNum() == null){
            Snowflake snowflake = IdUtil.getSnowflake(1, 1);
            long id = snowflake.nextId();
            collectWrit.setWritNum(String.valueOf(id));
        }
        if (EmptyUtil.isEmpty(collectWrit.getTitle())){
            throw new SecurityException("标题不能为空！");
        }
        if (EmptyUtil.isEmpty(collectWrit.getCollectUser())){
            throw new SecurityException("收件人不能为空！");
        }
        collectWrit.setNodeId(processNodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id",processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name","收文")).getId()).eq("sort_num","1")).getId());
        collectWrit.setProgress("同意");
        int pId = processNodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "收文")).getId()).eq("sort_num", "1")).getPId();
        Handle handle = new Handle();
        handle.setPId(pId);
        handle.setMiddlemanId(collectWrit.getOfficeId());
        if (collectWritMapper.insert(collectWrit)>0) {
            Handle handle1 = new Handle();
            handle1.setDocumentId(collectWrit.getId());
            handle1.setPId(pId);
            handle1.setHandleId(collectWrit.getCollectUserId());
            handleMapper.insert(handle1);
            handle.setDocumentId(collectWrit.getId());
            handleMapper.insert(handle);
        }
    }

    /**
     *流程运转
     *@author Hugo
     *@date 2021-04-28 14:54
     **/
    @Override
    public void examine(CollectWrit collectWrit, String nextId, String userId) {
        if (collectWrit.getNodeId()==0){
            throw new SecurityException("流程已经结束");
        }
        Integer maxNum = processNodeMapper.sortMax(processNodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("id", collectWrit.getNodeId())).getPId());
        int a = processRouterMapper.selectOne(new QueryWrapper<ProcessRouter>().eq("current_id",collectWrit.getNodeId()).eq("requirement",collectWrit.getProgress())).getTargetId();
        if (processNodeMapper.selectById(a).getSortNum().equals(maxNum)){
            collectWrit.setNodeId(0);
        }else {
            collectWrit.setNodeId(a);
        }
        // 更改上一个节点 代办和已办
        Map<String , Object> map = new HashMap<>(16);
        map.put("document_id",collectWrit.getId());
        map.put("middleman_id",userId);
        if (handleMapper.selectCount(new QueryWrapper<Handle>().allEq(map))>0){
            Handle handle = handleMapper.selectOne(new QueryWrapper<Handle>().allEq(map));
            handle.setHandleId(userId);
            handle.setMiddlemanId("");
            handleMapper.updateById(handle);
        }
        // 插入下一事项办理人代办和已办
        Handle handle = new Handle();
        handle.setPId(processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name","收文")).getId());
        handle.setDocumentId(collectWrit.getId());
        handle.setMiddlemanId(nextId);
        handle.setNId(a);
        handleMapper.insert(handle);
        baseMapper.updateById(collectWrit);
    }

    /**
     *收文代办
     *@author Hugo
     *@date 2021-04-28 15:42
     **/
    @Override
    public List<CollectWrit> pageUnCompleteList(int page, int limit, String userId) {
        int pId = processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "收文")).getId();
        List<Handle> handles = handleMapper.selectList(new QueryWrapper<Handle>().eq("middleman_id", userId).eq("p_id", pId));
        List<CollectWrit> publishes = new ArrayList<>();
        for (Handle handle : handles) {
            publishes.add(collectWritMapper.selectById(handle.getDocumentId()));
        }
        List<CollectWrit> currentPageList = new ArrayList<>();
        if (publishes != null && publishes.size() > 0) {
            int currIdx = (page > 1 ? (page - 1) * limit : 0);
            for (int i = 0; i < limit && i < publishes.size() - currIdx; i++) {
                currentPageList.add(publishes.get(currIdx + i));
            }
        }
        return currentPageList;
    }

    /**
     *显示已办事项
     *@author Hugo
     *@date 2021-04-28 16:11
     **/
    @Override
    public List<CollectWrit> pageCompleteList(int page, int limit, String userId) {
        int pId = processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "收文")).getId();
        List<Handle> handles = handleMapper.selectList(new QueryWrapper<Handle>().eq("handle_id", userId).eq("p_id", pId).or().eq("middleman_id",userId).eq("p_id", pId));
        List<CollectWrit> publishes = new ArrayList<>();
        for (Handle handle : handles) {
            publishes.add(collectWritMapper.selectById(handle.getDocumentId()));
        }
        List<CollectWrit> currentPageList = new ArrayList<>();
        if (publishes != null && publishes.size() > 0) {
            int currIdx = (page > 1 ? (page - 1) * limit : 0);
            for (int i = 0; i < limit && i < publishes.size() - currIdx; i++) {
                currentPageList.add(publishes.get(currIdx + i));
            }
        }
        return currentPageList;
    }

    @Override
    public List<CollectWrit> pageAllList(int page, int limit, String userId) {
        int pId = processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "收文")).getId();
        List<Handle> handles = handleMapper.selectList(new QueryWrapper<Handle>().eq("handle_id", userId).eq("p_id", pId).or().eq("middleman_id",userId).eq("p_id", pId));
        List<CollectWrit> publishes = new ArrayList<>();
        for (Handle handle : handles) {
            publishes.add(baseMapper.selectById(handle.getDocumentId()));
        }
        List<CollectWrit> currentPageList = new ArrayList<>();
        if (publishes != null && publishes.size() > 0) {
            int currIdx = (page > 1 ? (page - 1) * limit : 0);
            for (int i = 0; i < limit && i < publishes.size() - currIdx; i++) {
                currentPageList.add(publishes.get(currIdx + i));
            }
        }
        return currentPageList;

    }

}
